#include "mainwindow.h"
#include "jse/jse_manager.h"

#include <imgui.h>
#include <imgui_stdlib.h>
#include <quickjspp.hpp>
#include <vector>

main_window::main_window(int x, int y, int width, int height)
    : _x(x), _y(y), _width(width), _height(height)
{
  _env_id = javascript_manager::get().create_env();
}

void main_window::paint()
{
  static int g_ret = 0;
  ImGui::SetNextWindowSize(ImVec2(_width, _height));
  ImGui::SetNextWindowPos(ImVec2(_x, _y));
  if (ImGui::Begin("MainWindow", &_visible))
  {
    //错误提示
    ImGui::SetNextWindowContentSize(ImVec2(200, 50));
    if (ImGui::BeginPopup("ErrorPopup"))
    {
      ImGui::Text("javascript execute failed!");
      if (ImGui::Button("ok"))
      {
        ImGui::CloseCurrentPopup();
      }
      ImGui::EndPopup();
    }

    //消息框
    if (ImGui::BeginPopup("ERROR"))
    {
      ImGui::Text("Error!");
      if (ImGui::Button("Ok"))
      {
        ImGui::CloseCurrentPopup();
      }
      ImGui::EndPopup();
    }
    if (ImGui::BeginPopup("Result"))
    {
      ImGui::Text("iVal is: %d", g_ret);
      if (ImGui::Button("Ok"))
      {
        ImGui::CloseCurrentPopup();
      }
      ImGui::EndPopup();
    }

    ImGui::Text("Javascript code:");
    ImGui::SameLine();
    ImGui::InputText("##inputJavascript", &_javascript);
    ImGui::SameLine();
    if (ImGui::Button("Evecute") && _javascript.length())
    {
      qjs::Value ret = javascript_manager::get().eval_javascript_string(_env_id, _javascript);
      if (ret.isError())
      {
        ImGui::OpenPopup("ERROR");
      }
      else
      {
        g_ret = (int)ret;
        ImGui::OpenPopup("Result");
      }
    }

    ImGui::Text("execute javascript file:");
    ImGui::SameLine();
    ImGui::InputText("##filepath", &_filepath);
    ImGui::SameLine();
    if(ImGui::Button("Execute") && _javascript.length()) {
      qjs::Value ret = javascript_manager::get().eval_javascript_string(_env_id, _javascript);
    }



    ImGui::End();
  }
  else
  {
    _visible = false;
  }
}
